package br.com.mstecsystems.mavenpoc.persistence.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import br.com.mstecsystems.mavenpoc.model.User;
import br.com.mstecsystems.mavenpoc.persistence.PersistenceException;
import br.com.mstecsystems.mavenpoc.persistence.UserDAO;

public class UserHibernateDAO implements UserDAO {

	private SessionFactory sessionFactory;
	 
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
	
	@Override
	public void addUser(User user) {
		getSessionFactory().getCurrentSession().save(user);
	}

	@Override
	public void updateUser(User user) {
		getSessionFactory().getCurrentSession().update(user);
	}

	@Override
	public void deleteUser(User user) {
		getSessionFactory().getCurrentSession().delete(user);
	}

	@Override
	public User getUserById(int id) throws PersistenceException {
		Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(User.class);
		criteria.add(Restrictions.eq("id", id));
		List list = criteria.list();
		if(list == null || list.size() == 0){
			throw new PersistenceException("User not found!");
		}			
		return (User)list.get(0);
	}

	@Override
	public List<User> getUsers() {
        return getSessionFactory().getCurrentSession().createCriteria(User.class).list();
	}

}
